package advice.org.springframework.boot;

import com.dcits.agent.IAdvice;
import com.dcits.agent.utils.RedefineClassUtils;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
import org.kohsuke.MetaInfServices;
import org.springframework.boot.SpringApplication;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

/**
 * @className: SpringApplication
 * @description:
 * @author: caoyangjie
 * @date: 2025/6/9
 **/
@MetaInfServices
public class SpringApplicationAdvice implements IAdvice {
    public static final String[] TARGET_METHODS = {"getAllSources"};

    @Advice.OnMethodEnter
    static void onMethodEnter(@Advice.Origin Method method,
                             @Advice.AllArguments Object[] args,
                             @Advice.This SpringApplication thisInstance
                             ) {
        // 使用自定义的 ClassLoader
        Set<String> smartEmspBootstrap = thisInstance.getSources() == null ? new HashSet<>() : new HashSet<>(thisInstance.getSources());
        smartEmspBootstrap.add("cn.com.zybank.SmartBootstrap");
        smartEmspBootstrap.add("com.alibaba.cloud.sentinel");
        thisInstance.setSources(smartEmspBootstrap);
    }

    @Override
    public void advice() {
        // 这里需要根据实际情况填写 redefine 方法
        ElementMatcher<? super MethodDescription> matcher = ElementMatchers
                .namedOneOf(TARGET_METHODS); // 只匹配 TARGET_METHODS 中的方法
        // 增强当前类中所有的非构造函数的 public 方法
        RedefineClassUtils.redefineMethodWithAdvice(SpringApplication.class, matcher);
    }
}
